import 'package:dartkit/dartkit.dart';
import 'package:test/test.dart';

class People extends TreeNode<People> {
  String gender;
  People(this.gender);

  @override
  List<People> children = [];
}

void main() {
  late People child1;
  late People child2;
  late People child3;
  late People child4;
  late People parent1;
  late People parent2;
  late People root;

  setUp(() {
    root = People("man");

    parent1 = People("man");
    child1 = People("man");
    child2 = People("man");
    child3 = People("woman");

    parent2 = People("woman");
    child4 = People("woman");

    parent1.children.addAll([child1, child2, child3]);
    parent2.children.addAll([child4]);
    root.children.addAll([parent1, parent2]);
  });

  test("递归多重查找", () {
    // 不包括root自己，它有3个为man的child
    List<People> mans = root.findAll((node) => node.gender == "man");
    expect(mans.length, 4);
  });

  test("递归删除所有子节点", () {
    parent1.deleteAll((node) => node.gender == "man");
    expect(parent1.children.length, 1);
  });

  test("删除单个子节点", () {
    // 当有多个子节点满足条件时，应该报错
    expect(
        () => parent1.delete((node) => node.gender == "man"), throwsException);
  });

  test("正常删除单个子节点", () {
    parent1.delete((node) => node.gender == "woman");
    expect(parent1.children.length, 2);
  });

  test("注入节点", () {
    final newPeople = People("middle");
    parent1.insert((node) => node.gender == "woman", newPeople);

    expect(root.find((node) => node.gender == "middle"), isA<People>());
  });

  test("递归执行操作", () {
    root.forEach((node) => node.gender += "ha");
    expect(child4.gender, "womanha");
  });

  test("递归累加操作", () {
    // 统计家里的总人口数
    int numPeople = root.sum<int>(0, (total, _) => total + 1);
    expect(numPeople, 7);
  });
}
